﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using System.Data;
using System.Transactions;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.Mtbl;
using HKEA.CMS.Core.BLL.App;
namespace WebApplication
{
    public partial class M_Brand :BasePage
    {
        #region 写入log
        static app_mtblBrand entBrandLog = new app_mtblBrand();
        static List<int> GetCheckList = new List<int>();
        static string MedioBrand;
        #endregion

        tblCustomer customerENT = new tblCustomer();
        int CustomerUID = 0;
        protected string type = "";
        private string isfromApp = string.Empty;
        app_tblMediaRoomBLL app_mediaBLL = new app_tblMediaRoomBLL();
        tblMediaRoomBLL mediaBLL = new tblMediaRoomBLL();
        app_tblMediaRoom_RelatedBLL app_relatedBLL = new app_tblMediaRoom_RelatedBLL();
        tblMediaRoomRelatedBLL tbl_relatedBLL = new tblMediaRoomRelatedBLL();
        protected int ctuid = 0;
        mtblBrandBLL tbl_brandBLL = new mtblBrandBLL();
        app_mtblBrandBLL app_brandBLL = new app_mtblBrandBLL();
        int app_branduid = 0;
        int tbl_branduid = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                customerENT = GetCustomerFromSession();
                if (customerENT != null)
                {
                    hidCustomerUID.Value = customerENT.CustomerUID.ToString();
                    CustomerUID = customerENT.CustomerUID;
                    InitPage();
                }
                else
                { CustomerNotLoginOption(); }
                BindStaticEnt();
            }
        }

        private void InitPage()
        {
            type = Request.QueryString["type"];
            BindProductCat();
            BindBrandList();
            BindBrandImg();
            string strctuid = Request.QueryString[Constant.UrlParamName.custToContactPersonUID];
            string strfrom = Request.QueryString[Constant.UrlParamName.IsFromApp];
            if (strctuid != null && strfrom != null)
            {
                lkQuit.NavigateUrl = lkAdd.NavigateUrl = "/M_Brand.aspx?type=add";
                int.TryParse(strctuid, out ctuid);
                if (ctuid > 0)
                {
                    if (Request.QueryString[Constant.UrlParamName.IsFromApp].ToLower() == "true")
                    {
                        SetFormFromApp(ctuid);
                    }
                    else if (Request.QueryString[Constant.UrlParamName.IsFromApp].ToLower() == "false")
                    {
                        app_mtblBrand app_brand = new app_mtblBrand();
                        app_brand.AppBrandUID = ctuid;
                        app_brand.Deleted = 0;
                        app_brand.CustomerUID = CustomerUID;
                        app_brand = app_brandBLL.GetEntity(app_brand,false);
                        if (app_brand != null)
                        {
                            if (app_brand.Deleted == 1)
                            {
                                SetNoOption(); lblMeg.Text = ResourceManage.GetResourceString("msg200014"); return;
                            }
                            else
                            {
                                ctuid = app_brand.AppBrandUID;
                                SetFormFromApp(ctuid);
                            }
                        }
                        else
                        { SetFormFromTbl(ctuid); }
                    }
                }
                else
                { SetNoOption(); lblMeg.Text = ResourceManage.GetResourceString("msg200001"); return; }
            }
        }


        private void SetFormFromApp(int ctuid)
        {
            app_mtblBrand app_brand = new app_mtblBrand();
            app_brand.Deleted = 0;
            app_brand.CustomerUID = CustomerUID;
            app_brand.AppBrandUID = ctuid;
            app_brand = app_brandBLL.GetEntity(app_brand, true);
            if (app_brand != null)
            {
                if (app_brand.BrandUID > 0)
                    tbl_branduid = (int)app_brand.BrandUID;
                hidRelatedBrandProdCatStrUID.Value = GetCatFromApp(ctuid);
                txtBrandIntro_Chi.Text = app_brand.Intro_Chi;
                txtBrandIntro_Eng.Text = app_brand.Intro_Eng;
                txtBrandName_Chi.Text = app_brand.BrandName_Chi;
                txtBrandName_Eng.Text = app_brand.BrandName_Eng;
                var ListSource = new List<MediaRoomList>();
                if (app_brand.BrandLogo > 0)
                {
                    tblMediaRoom mediaroomENT = new tblMediaRoom();
                    tblMediaRoomBLL mediaroomBLL = new tblMediaRoomBLL();
                    mediaroomENT.CustomerUID = Convert.ToInt32(CustomerUID);
                    mediaroomENT.MediaRoomUID = (int)app_brand.BrandLogo;
                    var tblList = mediaroomBLL.GetList(mediaroomENT, null);
                    if (tblList != null)
                    {
                        var tempent = tblList.FirstOrDefault();
                        if (tempent != null)
                        {
                            hidMediaRoomStr.Value = tempent.KeyInfo;
                            ListSource.Add(tempent);
                        }
                    }
                }
                else if(app_brand.AppMediaUIDBrandLogo > 0)
                {
                    app_tblMediaRoom app_media = new app_tblMediaRoom();
                    app_media.CustomerUID = CustomerUID;
                    app_media.AppMediaRoomUID = (int)app_brand.AppMediaUIDBrandLogo;
                    var appList = app_mediaBLL.GetList(app_media, true);
                    if (appList != null)
                    {
                        ListSource.Add(appList.FirstOrDefault());
                    }
                }
                rptRelatedImgList.DataSource = ListSource;
                rptRelatedImgList.DataBind();
            }
            else
            { SetNoOption(); lblMeg.Text = ResourceManage.GetResourceString("msg200014"); return; }
        }
        private void SetFormFromTbl(int ctuid)
        {
            mtblBrand tbl_brand = new mtblBrand();
            tbl_brand.Deleted = 0;
            tbl_brand.CustomerUID = CustomerUID;
            tbl_brand.BrandUID = ctuid;
            tbl_brand = tbl_brandBLL.GetEntity(tbl_brand);
            if (tbl_brand != null)
            {
                app_mtblBrand app_brand = new app_mtblBrand();
                app_brand.CustomerUID = CustomerUID;
                app_brand.BrandUID = ctuid;
                app_brand = app_brandBLL.GetEntity(app_brand,false);
                if (app_brand != null)
                {
                    Response.Redirect("/M_Brand.aspx?ctcuid=" + app_brand.AppBrandUID + "&isFromApp=True");
                    return;
                }

                List<int> without = new List<int>();
                hidRelatedBrandProdCatStrUID.Value = GetCatFromTbl(ctuid, without);
                txtBrandIntro_Chi.Text = tbl_brand.Intro_Chi;
                txtBrandIntro_Eng.Text = tbl_brand.Intro_Eng;
                txtBrandName_Chi.Text = tbl_brand.BrandName_Chi;
                txtBrandName_Eng.Text = tbl_brand.BrandName_Eng;
                var ListSource = new List<MediaRoomList>();
                if (tbl_brand.BrandLogo > 0)
                {
                    tblMediaRoom mediaroomENT = new tblMediaRoom();
                    tblMediaRoomBLL mediaroomBLL = new tblMediaRoomBLL();
                    mediaroomENT.CustomerUID = Convert.ToInt32(CustomerUID);
                    mediaroomENT.MediaRoomUID = (int)tbl_brand.BrandLogo;
                    var tblList = mediaroomBLL.GetList(mediaroomENT, null);
                    if (tblList != null)
                    {
                        var tempent=tblList.FirstOrDefault();
                        if (tempent != null)
                        {
                            hidMediaRoomStr.Value = tempent.KeyInfo;
                            ListSource.Add(tblList.FirstOrDefault());
                        }
                    }
                }
                rptRelatedImgList.DataSource = ListSource;
                rptRelatedImgList.DataBind();
            }
            else
            { SetNoOption(); lblMeg.Text = ResourceManage.GetResourceString("msg200014"); return; }
        }

        private void SetNoOption()
        {
            hidAllowOption.Value = "false";
            lkBtnSave.Enabled = false;
        }
        private void BindProductCat()
        {
            List<string> strlist = new List<string>();
            strlist.Add("A");
            strlist.Add("B");
            strlist.Add("C");
            strlist.Add("D");
            strlist.Add("E");
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn();
            col.ColumnName = "startwith";
            dt.Columns.Add(col);
            foreach (var temp in strlist)
            {
                DataRow dr = dt.NewRow();
                dr[0] = temp;
                dt.Rows.Add(dr);
            }
            rptStart.DataSource = dt;
            rptStart.DataBind();
        }
        private void BindBrandList()
        {
            var app_brandAll = customerENT.app_mtblBrand;
            customerENT.app_mtblBrand.Load();
            //var cust_cpAll = customerENT.tblCust_ContactPerson.Where(a => a.Deleted == 0).ToList(); //查询 Customer的CP所有未被删除的记录
            List<int> withOutList = new List<int>();
            //遍历被Memeber操作的数据，循环出tbl中的数据； 即：app表除新增数据外的其他记录
            foreach (var temp in app_brandAll.Where(a => a.BrandUID > 0).ToList())
            {
                withOutList.Add((int)temp.BrandUID);
            }

            List<M_BrandListDetail> listValue = new List<M_BrandListDetail>();
            List<M_BrandListDetail> tblData = tbl_brandBLL.GetListByCustUID(withOutList, CustomerUID);
            List<M_BrandListDetail> appData = app_brandBLL.GetListByENT(customerENT.CustomerUID);
            listValue.AddRange(tblData);
            listValue.AddRange(appData);
            rptBrandList.DataSource = listValue;
            rptBrandList.DataBind();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "AverageBrand();", true);
        }
        private void BindBrandImg()
        {
            app_tblMediaRoom app_media = new app_tblMediaRoom();
            app_media.CustomerUID = CustomerUID;
            app_media.MediaType = Constant.MediaType.image;
            app_media.Category = Constant.MediaRoomCategory.brand_logo;
            var appALLList = app_mediaBLL.GetList(app_media, false);
            List<int> withOutList = new List<int>();
            foreach (var temp in appALLList.Where(a => a.TblKeyUID > 0).ToList())
            {
                withOutList.Add(temp.TblKeyUID);
            }
            var appList = appALLList.Where(a => a.IsDeleted == 0).ToList();

            tblMediaRoom mediaroomENT = new tblMediaRoom();
            tblMediaRoomBLL mediaroomBLL = new tblMediaRoomBLL();
            mediaroomENT.CustomerUID = Convert.ToInt32(CustomerUID);
            mediaroomENT.MediaType = Constant.MediaType.image;
            mediaroomENT.Category = Constant.MediaRoomCategory.brand_logo;
            var tblList = mediaroomBLL.GetList(mediaroomENT, withOutList);
            var ListSource = new List<MediaRoomList>();
            ListSource.AddRange(appList);
            ListSource.AddRange(tblList);
            rptImgList.DataSource = ListSource;
            rptImgList.DataBind();
        }

        protected string GetCatFromApp(int appBrandUID)
        {
            string str = string.Empty;

            app_tblBrand_ProdCat app_brandcat = new app_tblBrand_ProdCat();
            app_tblBrand_ProdCatBLL app_brandcatBLL = new app_tblBrand_ProdCatBLL();
            app_brandcat.AppBrandUID = appBrandUID;
            var app_CatAll = app_brandcatBLL.GetListByENT(app_brandcat, false);
            foreach (var temp in app_CatAll)
            {
                if (temp.Deleted == 0)
                    str += temp.ProductCatUID +",";
            }
            var withOutList = app_CatAll.Where(a => a.Deleted == 1).Where(a => a.BrandProdCatUID > 0).ToList().Select(a => (int)a.BrandProdCatUID).ToList();
            if (tbl_branduid > 0)
            {
                str += GetCatFromTbl(tbl_branduid, withOutList);
            }
            return str;
        }
        // TODO CheckBox赋值
        protected string GetCatFromTbl(int brandUID, List<int> withOutList) //withOutUID 表示：主键集合
        {
            string str = string.Empty;
            if (brandUID > 0)
            {
                tblBrand_ProdCat tbl_brandcat = new tblBrand_ProdCat();
                tblBrand_ProdCatBLL tbl_brandcatBLL = new tblBrand_ProdCatBLL();
                tbl_brandcat.BrandUID = brandUID;
                tbl_brandcat.Deleted = 0;
                var JobAll = tbl_brandcatBLL.GetList(tbl_brandcat, withOutList); 
                foreach (var temp in JobAll)
                {
                    str += temp.ProductCatUID + ",";
                }
            }
            return str;
        }

        protected void lkBtnSave_Click(object sender, EventArgs e)
        {
            customerENT = GetCustomerFromSession();
            if (customerENT != null)
            {
                CustomerUID = customerENT.CustomerUID;
                string strctcuid = Request.QueryString[Constant.UrlParamName.custToContactPersonUID];
                type = Request.QueryString["type"];
                isfromApp = Request.QueryString[Constant.UrlParamName.IsFromApp];
                if (!string.IsNullOrEmpty(strctcuid) && int.TryParse(strctcuid, out ctuid) && ctuid > 0 && !string.IsNullOrEmpty(isfromApp))
                {
                    Update();
                }
                else
                {
                    Add();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "cleartxt", "ClearText();", true);
                }
                PageIsPostBack();
                WriteToLog();
            }
        }
        private void PageIsPostBack()
        {
            BindBrandList();
        }

        protected void Update()
        {
            string strIsFromApp = Request.QueryString[Constant.UrlParamName.IsFromApp];
            if (!string.IsNullOrEmpty(strIsFromApp))
            {
                if (strIsFromApp.ToLower().Trim() == "true")
                    UpdateApp();
                else
                    AddToAppFromTbl();
            }
            else
            { lblMeg.Text = ResourceManage.GetResourceString("msg200017"); }
        }

        private void UpdateApp()
        {
            #region 修改
            app_mtblBrand app_brand = new app_mtblBrand();
            app_brand.Deleted = 0;
            app_brand.CustomerUID = CustomerUID;
            app_brand.AppBrandUID = ctuid;
            app_brand = app_brandBLL.GetEntity(app_brand,true);
            if (app_brand != null)
            {
                app_branduid = app_brand.AppBrandUID;
                if (app_brand.BrandUID > 0)
                    tbl_branduid = (int)app_brand.BrandUID;
                app_brand = GetApp_BrandENT(app_brand);

                List<int> ToDeleted = new List<int>(); //本地需要被物理删除的记录 (App表主键)
                List<app_tblBrand_ProdCat> AddToDeleted = new List<app_tblBrand_ProdCat>(); //本次需要被新增到app做删除标记的记录(ProductCatUID)
                List<app_tblBrand_ProdCat> Add = new List<app_tblBrand_ProdCat>();
                app_tblBrand_ProdCatBLL app_catBLL = new app_tblBrand_ProdCatBLL();
                DetchCat(ToDeleted, AddToDeleted, Add);
                TransactionOptions options = new TransactionOptions();
                    options.Timeout = new TimeSpan(0, 5, 0);
                    options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                    {
                        app_brandBLL.UpdateENT(app_brand);
                        app_catBLL.SaveList(ToDeleted, AddToDeleted, Add);
                        PageIsPostBack();
                        try
                        {
                            scope.Complete();
                            lblMeg.Text = ResourceManage.GetResourceString("msg200004");
                        }
                        catch (Exception er)
                        { lblMeg.Text = ResourceManage.GetResourceString("msg200003"); }
                    }
            }
            else
            { lblMeg.Text = ResourceManage.GetResourceString("msg200014"); }
            #endregion
        }
        
        private void AddToAppFromTbl()
        {
           
            mtblBrand tbl_brand = new mtblBrand();
            tbl_brand.CustomerUID = CustomerUID;
            tbl_branduid = tbl_brand.BrandUID = ctuid;
            tbl_brand.Deleted = 0;
            tbl_brand = tbl_brandBLL.GetEntity(tbl_brand);
            if (tbl_brand == null)
            {
                lblMeg.Text = ResourceManage.GetResourceString("msg200013");
                return;
            }
            else
            {
                app_mtblBrand app_brand = new app_mtblBrand();
                app_brand.BrandUID = ctuid;
                app_brand.CustomerUID = CustomerUID;
                var tempENT = app_brandBLL.GetEntity(app_brand, false);
                if (tempENT == null)
                {
                    Add();
                }
                else
                {
                    app_branduid = app_brand.AppBrandUID;
                    if (app_brand.BrandUID > 0)
                        tbl_branduid = (int)app_brand.BrandUID;
                    if (tempENT.Deleted == 1)
                    {
                        lblMeg.Text = ResourceManage.GetResourceString("msg200014");
                        return;
                    }
                    else
                    {
                        app_branduid = ctuid = tempENT.AppBrandUID;
                        UpdateApp();
                    }
                }
            }
        }
        protected void Add()
        {
            app_mtblBrand app_brand = new app_mtblBrand();
            app_brand.CustomerUID = CustomerUID;
            if (tbl_branduid > 0)
            {
                app_brand.BrandUID = tbl_branduid;
                var temp = app_brandBLL.GetEntity(app_brand, false);
                if (temp != null && ctuid > 0 && type != "add")
                {
                    if (temp.Deleted == 0)
                    {
                        ctuid= app_branduid = temp.AppBrandUID;
                        UpdateApp();
                        return;
                    }
                    else
                    {
                        lblMeg.Text = ResourceManage.GetResourceString("msg200014");
                        return;
                    }
                }
            }
            app_brand = GetApp_BrandENT(app_brand);

            List<int> ToDeleted = new List<int>(); //本地需要被物理删除的记录 (App表主键)
            List<app_tblBrand_ProdCat> AddToDeleted = new List<app_tblBrand_ProdCat>(); //本次需要被新增到app做删除标记的记录(ProductCatUID)
            List<app_tblBrand_ProdCat> Add = new List<app_tblBrand_ProdCat>();
            app_tblBrand_ProdCatBLL app_catBLL = new app_tblBrand_ProdCatBLL();

            TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 5, 0);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                app_branduid = app_brandBLL.InsertENT(app_brand);
                DetchCat(ToDeleted, AddToDeleted, Add);
                app_catBLL.SaveList(ToDeleted, AddToDeleted, Add);
                PageIsPostBack();
                try
                {
                    scope.Complete();
                    lblMeg.Text = ResourceManage.GetResourceString("msg200004");
                }
                catch (Exception er)
                { lblMeg.Text = ResourceManage.GetResourceString("msg200003"); }
            }
        }
        private List<int> GetChecked()
        { return GetList(hidRelatedBrandProdCatStrUID); }
        
        private app_mtblBrand GetApp_BrandENT(app_mtblBrand ent)
        {
            ent.BrandName_Eng = txtBrandName_Eng.Text;
            ent.BrandName_Chi = txtBrandName_Chi.Text;
            ent.Intro_Chi = txtBrandIntro_Chi.Text;
            ent.Intro_Eng = txtBrandIntro_Eng.Text;
            string strMedia = hidMediaRoomStr.Value;
            if (!string.IsNullOrEmpty(strMedia))
            {
                string[] info = strMedia.Split('_');
                string strFrom = info[1];
                int mediaKey = Convert.ToInt32(info[0]);
                if (strFrom == "tbl")
                {
                    ent.BrandLogo = mediaKey;
                    ent.AppMediaUIDBrandLogo = null;
                }
                else
                {
                    ent.AppMediaUIDBrandLogo = mediaKey;
                    ent.BrandLogo = null;
                }
            }
            else
            {
                ent.AppMediaUIDBrandLogo = null;
                ent.BrandLogo = null;
            }
            return ent;
        }
        protected List<int> GetList(HiddenField name)
        {
            List<int> ret = new List<int>();
            if (!string.IsNullOrEmpty(name.Value))
            {
                ret = name.Value.StringToList();
            }
            return ret;
        }
        protected List<tblBrand_ProdCat> GetTBLCat()
        {
            if (tbl_branduid > 0)
            {
                tblBrand_ProdCat catent = new tblBrand_ProdCat();
                tblBrand_ProdCatBLL bll = new tblBrand_ProdCatBLL();
                catent.BrandUID = tbl_branduid;
                catent.Deleted = 0;
                return bll.GetListByENT(catent);
            }
            return null;
        }
        protected List<app_tblBrand_ProdCat> GetAppCat()
        {
            if (app_branduid > 0)
            {
                app_tblBrand_ProdCat catent = new app_tblBrand_ProdCat();
                app_tblBrand_ProdCatBLL bll = new app_tblBrand_ProdCatBLL();
                catent.AppBrandUID = app_branduid;
                return bll.GetListByENT(catent, false);
            }
            return null;
        }
        private void DetchCat(List<int> ToDeleted, List<app_tblBrand_ProdCat> AddToDeleted, List<app_tblBrand_ProdCat> Add)
        {
            var CheckedList = GetChecked();
            var tbl_List = GetTBLCat();
            var app_List = GetAppCat();
            #region tbl_list处理
            if (tbl_List != null && tbl_List.Count > 0)
            {
                foreach (var temp in tbl_List)
                {
                    if (!CheckedList.Contains((int)temp.ProductCatUID)) //需要被添加到APP做删除标记的TBL记录
                    {
                        if (app_List != null)
                        {
                            if (app_List.Where(a => a.ProductCatUID == (int)temp.ProductCatUID).Where(a => a.Deleted == 1).ToList().Count == 0)
                            {
                                app_tblBrand_ProdCat ent = new app_tblBrand_ProdCat();
                                if (app_branduid > 0)
                                    ent.AppBrandUID = app_branduid;
                                if (tbl_branduid > 0)
                                    ent.BrandUID = tbl_branduid;
                                ent.BrandProdCatUID = temp.BrandProdCatUID;
                                ent.Deleted = 1;
                                ent.ProductCatUID = (int)temp.ProductCatUID;
                                AddToDeleted.Add(ent);
                            }
                        }
                        else
                        {
                            app_tblBrand_ProdCat ent = new app_tblBrand_ProdCat();
                            if (app_branduid > 0)
                                ent.AppBrandUID = app_branduid;
                            if (tbl_branduid > 0)
                                ent.BrandUID = tbl_branduid;
                            ent.BrandProdCatUID = temp.BrandProdCatUID;
                            ent.Deleted = 1;
                            ent.ProductCatUID = (int)temp.ProductCatUID;
                            AddToDeleted.Add(ent);
                        }
                    }
                }
            }
            #endregion
            #region app_list处理
            if (app_List != null && app_List.Where(a => a.Deleted == 0).ToList().Count > 0) //存在新增App数据，被取消
            {
                foreach (var temp in app_List.Where(a => a.Deleted == 0).ToList())
                {
                    if (!CheckedList.Contains((int)temp.ProductCatUID))
                    {
                        ToDeleted.Add(temp.AppBrandProdCatUID);
                    }
                }
            }
            #endregion
            # region checkList处理
            if (CheckedList.Count > 0)
            {
                foreach (var temp in CheckedList)
                {
                    bool NeedToAdd = true;
                    if (app_List != null && app_List.Count > 0)
                    {
                        var tempApp = app_List.Where(a => a.ProductCatUID == temp).Where(a => a.Deleted == 1).FirstOrDefault();
                        if (tempApp != null)
                            ToDeleted.Add(tempApp.AppBrandProdCatUID);
                        else if (app_List.Where(a => a.ProductCatUID == temp).Where(a => a.Deleted == 0).FirstOrDefault() != null)
                        {
                            NeedToAdd = false;
                        }
                    }
                    if (tbl_List != null && tbl_List.Count > 0)
                    {
                        var tempTbl = tbl_List.Where(a => a.ProductCatUID == temp).Where(a => a.Deleted == 0).FirstOrDefault();
                        if (tempTbl != null)
                        {
                            NeedToAdd = false;
                        }
                    }
                    if (NeedToAdd)
                    {
                        app_tblBrand_ProdCat ent = new app_tblBrand_ProdCat();
                        if (app_branduid > 0)
                            ent.AppBrandUID = app_branduid;
                        if (tbl_branduid > 0)
                            ent.BrandUID = tbl_branduid;
                        ent.Deleted = 0;
                        ent.ProductCatUID = temp;
                        Add.Add(ent);
                    }
                }
            }
            #endregion
        }

        //Customer上传图片，刷新图片列表触发事件
        protected void btnRefreshImgList_Click(object sender, EventArgs e)
        {
            customerENT = GetCustomerFromSession();
            if (customerENT != null)
            {
                CustomerUID = customerENT.CustomerUID;
                BindBrandImg();
            }
            else
            { lblMeg.Text = ResourceManage.GetResourceString("msg200016"); }
        }
        //刷新BrandList列表触发事件
        protected void btnRefreshBrandList_Click(object sender, EventArgs e)
        {
            var tempent=GetCustomerFromSession();
            if (tempent != null)
            {
                customerENT = tempent;
                BindBrandList();
            }
        }
        protected void rptStart_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            string ProductCatID = (string)((DataRowView)e.Item.DataItem)["startwith"];
            Repeater rptCat = e.Item.FindControl("rptCat") as Repeater;
            Repeater rptCatForSubCat = e.Item.FindControl("rptCatForSubCat") as Repeater;
            if (rptCat != null)
            {

                mtblProductCat catENT = new mtblProductCat();
                mtblProductCatBLL catBLL = new mtblProductCatBLL();
                catENT.ProductCatID = ProductCatID;
                catENT.Deleted = 0;
                var list = catBLL.GetListByENT(catENT);
                rptCat.DataSource = list;
                rptCat.DataBind();
                rptCatForSubCat.DataSource = list;
                rptCatForSubCat.DataBind();
            }
        }
        protected void rptRelatedImgList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Literal ltImg = e.Item.FindControl("ltImg") as Literal;
                MediaRoomList tempENT = e.Item.DataItem as MediaRoomList;
                string KeyValue = string.Empty;
                if (tempENT != null)
                {
                    string From = tempENT.From;
                    int MediaRoomKeyUID = Convert.ToInt32(tempENT.KeyUID);
                    string strImgUrl = string.Empty;
                    if (From == "app")
                    {
                        app_tblMediaRoom_Related app_related = new app_tblMediaRoom_Related();
                        app_related.AppMediaRoomRelatedUID = MediaRoomKeyUID;
                        app_related = app_relatedBLL.GetListByENT(app_related).FirstOrDefault();
                        if (app_related != null)
                        {
                            if (app_related.AppMediaRoomUID > 0)
                            {
                                app_tblMediaRoom app_room = new app_tblMediaRoom();
                                app_room.AppMediaRoomUID = (int)app_related.AppMediaRoomUID;
                                app_room = app_mediaBLL.GetListByENT(app_room).FirstOrDefault();
                                if (app_room != null)
                                {
                                    strImgUrl = "<img src=\"" + app_room.FilePath + app_room.FileName + "_150_150.jpg \"/>";
                                }
                            }
                            else if (app_related.tblMediaRoom != null)
                            {
                                var temp = app_related.tblMediaRoom;
                                strImgUrl = "<img src=\"" + temp.FilePath + temp.FileName + "_150_150.jpg \"/>";
                            }
                        }
                    }
                    else
                    {
                        tblMediaRoom_Related tbl_related = new tblMediaRoom_Related();
                        tbl_related.MediaRoomRelatedUID = MediaRoomKeyUID;
                        tbl_related = tbl_relatedBLL.GetListByENT(tbl_related).FirstOrDefault();
                        if (tbl_related != null && tbl_related.tblMediaRoom != null)
                        {
                            var temp = tbl_related.tblMediaRoom;
                            strImgUrl = "<img src=\"" + temp.FilePath + temp.FileName + "_150_150.jpg \"/>";
                        }

                    }
                    ltImg.Text = strImgUrl;
                }
            }
        }
        protected void rptCatForSubCat_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                Repeater rptSubCat = e.Item.FindControl("rptSubCat") as Repeater;
                if (rptSubCat != null)
                {
                    mtblProductCat catENT = new mtblProductCat();
                    catENT = e.Item.DataItem as mtblProductCat;
                    mtblProductSubCat subCatENT = new mtblProductSubCat();
                    mtblProductSubCatBLL subCatBLL = new mtblProductSubCatBLL();
                    subCatENT.ProductCatUID = catENT.ProductCatUID;
                    subCatENT.Deleted = 0;
                    var list = subCatBLL.GetListByENT(subCatENT);
                    rptSubCat.DataSource = list;
                    rptSubCat.DataBind();
                }
            }
        }       

        #region
        protected void WriteToLog()
        {
            string info = string.Empty;
            info += CheckChange(info);
            info += ProductSubCatChange(info);
            tblUser ent = GetManageFromSession();
            Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
            tblHistory entlog = new tblHistory();
            entlog.HistoryCatUID = 2;
            entlog.HistoryTypeUID = 26;
            entlog.CustomerUID = GetEnt();
            entlog.Cust_MemberUID = 0;
            entlog.ContactPersonUID = 0;
            entlog.History_Detail = ent.User_Name + " {" + CompanyName.Text + "}{BusinessNature}" + info;
            entlog.LastModifyBy = ent.User_Name;
            int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
        }
        
        /// <summary>
        /// 写入Log
        /// </summary>
        private void BindStaticEnt()
        {
            GetCheckList.Clear();
            entBrandLog = GetApp_BrandENT(entBrandLog);
            GetCheckList = GetChecked();
            MedioBrand = hidMediaRoomStr.Value;
        }
        /// <summary>
        /// 检查已经改变的数据
        /// </summary>
        /// <returns></returns>
        private string CheckChange(string info)
        {
            string tempMedioBrand = hidMediaRoomStr.Value;
            app_mtblBrand ent = new app_mtblBrand();
            ent = GetApp_BrandENT(ent);
            if (entBrandLog.BrandName_Chi != ent.BrandName_Chi)
                info += "品牌名稱 change to " + ent.BrandName_Chi;
            if (entBrandLog.BrandName_Eng != ent.BrandName_Eng)
                info += "Brand Name change to " + ent.BrandName_Eng;
            if (entBrandLog.Intro_Chi != ent.Intro_Chi)
                info += "品牌簡介 changge to " + ent.Intro_Chi;
            if (entBrandLog.Intro_Eng != ent.Intro_Eng)
                info += "Brand Description change to " + ent.Intro_Eng;
            if (MedioBrand.Trim() != tempMedioBrand.Trim())
                info += "Brand image have change";
            return info;
        }
        private string ProductSubCatChange(string info)
        {
            List<int> add = new List<int>(GetChangeList(GetChecked(), GetCheckList));
            List<int> delete = new List<int>(GetChangeList(GetCheckList, GetChecked()));

            mtblProductSubCat entProSubCat = new mtblProductSubCat();

            List<mtblProductSubCat> list = mtblProductSubCatBLL.GetInstance().GetListByENT(entProSubCat);
            string tempAddList = string.Empty;
            for (int i = 0; i < add.Count - 1; i++)
            {
                var result = list.Where(a => a.ProductCatUID == Convert.ToInt32(add[i])).Select(p => p).ToList();
                foreach (mtblProductSubCat item in result)
                {
                    tempAddList += item.ProductSubCat_Eng + ",";
                }
            }
            if (info.Length > 5)
                info += "ProductSubCat have add:" + tempAddList;
            string tempDelList = string.Empty;
            for (int i = 0; i < delete.Count - 1; i++)
            {
                var result = list.Where(a => a.ProductCatUID == Convert.ToInt32(delete[i])).Select(p => p).ToList();
                foreach (mtblProductSubCat item in result)
                {
                    tempDelList += item.ProductSubCat_Eng + ",";
                }
            }
            if (tempDelList.Length > 5)
                info += "ProductSubCat have delete: " + tempDelList;

            return info;
        }
        
        /// <summary>
        /// 返回有差别的数据
        /// </summary>
        /// <param name="New">需要取出不一样数据的数组</param>
        /// <param name="Source">需要比对的源数组</param>
        /// <returns></returns>
        private List<int> GetChangeList(List<int> Contrast, List<int> Source)
        {
            List<int> add = new List<int>();
            for (int i = 0; i < Contrast.Count(); i++)
            {
                bool has = Source.Contains(Contrast[i]);
                if (has == false)
                    add.Add(Contrast[i]);
            }
            return add;
        }
        #endregion
    }
}